﻿using MediatR;
using SystemWFH.API.Application.Command.EquipmentCommand;
using SystemWFH.Infrstructer.Interface;

namespace SystemWFH.API.Application.CommandHandlers.EquipmentCommandHandler
{

    public class EquipmentStateCommandHandler : IRequestHandler<EquipmentStateCommand, int>
    {
        /// <summary>
        /// 服务
        /// </summary>
        private readonly IEquipmentRepository equipmentRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="equipmentRepository">服务</param>
        public EquipmentStateCommandHandler(IEquipmentRepository equipmentRepository)
        {
            this.equipmentRepository = equipmentRepository;
        }
        public async Task<int> Handle(EquipmentStateCommand request, CancellationToken cancellationToken)
        {
            // 获取设备的当前状态
            var str = await equipmentRepository.GetValue(request.equipmentId);

            // 根据业务逻辑修改设备状态
            // 假设你有一个方法来决定新的状态值
            int newStatus = DetermineNewStatus(str.equipmentState);

            // 更新设备状态
            str.equipmentState = newStatus;

            // 保存修改后的设备状态
            await equipmentRepository.UpdateAsync(str);

            // 返回新的状态值
            return newStatus;
        }
        private int DetermineNewStatus(int currentStatus)
        {
            // 这里根据你的业务逻辑来决定新的状态值
            // 例如，如果当前状态是1，则新的状态是2；如果当前状态是2，则新的状态是1
            if (currentStatus == 1)
            {
                return 2;
            }
            else if (currentStatus == 2)
            {
                return 1;
            }
            else
            {
                // 处理其他状态或抛出异常
                throw new InvalidOperationException("Invalid equipment state");
            }
        }
    }
}
